//
//  EmotionManager.swift
//  表情包数据
//
//  Created by zhanglongtao on 17/1/6.
//  Copyright © 2017年 hanju001. All rights reserved.
//vfvvdv

import Foundation
import UIKit

class EmotionManager {
    
    //为了便于表情的服用，建立一个单利只加载一次表情
    //表情管理器的单例
    static let shared = EmotionManager()
    //表情包的懒加载数组 -第一个数组是最近表情，加载之后，表情数组为空
    lazy var packages = [ZLEmotionPackage]()
    
    //表情素材bundle
    lazy var bundle: Bundle = {
       
        let path = Bundle.main.path(forResource: "HMEmoticon", ofType: "bundle")
        return Bundle(path: path!)!
        
    }()
    
    //构造函数 如果在init之前增加private修饰符 要求调用必须使用sahred
    private init() {
        
        loadPackages()
    }
    func recentEmotion(em: ZLEmotion) {
        em.times += 1
        if !packages[0].emtions.contains(em){
            
            packages[0].emtions.append(em)
        }
        //packages[0].emtions.sort { (em1, em2) -> Bool in
            
           // return em1.times > em2.times
        //}
        packages[0].emtions.sort { $0.times > $1.times }//排序的简写
        
        if (packages[0].emtions.count > 20){
            
            packages[0].emtions.removeLast()
        }
        
    }
}
extension EmotionManager {
    
    func emotionString(string: String, font: UIFont) -> NSAttributedString {
        
        let attrString = NSMutableAttributedString(string: string)
        let pattern = "\\[.*?\\]"
        guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else {
            
            return attrString
        }
        
        let matches = regex.matches(in: string, options: [], range: NSRange(location: 0, length: string.characters.count))
        /**
         注意应该倒序遍历
         */
        for m in matches.reversed() {
            let r = m.rangeAt(0)
            let subStr = (attrString.string as NSString).substring(with: r)
            //使用subStr查找对应的表情符号
            if let em = EmotionManager.shared.findEmotion(string: subStr) {
                
                //使用表情符号属性文本  替换原有的属性文本内容
                attrString.replaceCharacters(in: r, with: em.imageText(font: font))
            }
            
        }
        // 统一设置一遍字符串的属性
        attrString.addAttributes([NSFontAttributeName: font, NSForegroundColorAttributeName: UIColor.darkGray], range: NSRange(location: 0, length: attrString.length))
        
        return attrString
        
    }
    
    func findEmotion(string: String) -> ZLEmotion? {
        
        
        for p in packages {
            
            let result = p.emtions.filter({ (em) -> Bool in
                
                return em.chs == string
            })
            if result.count == 1{
                
                return result[0]
            }
        }
        
        return nil
    }
}

private extension EmotionManager {
    
    func loadPackages() {
        
        //读取emtion.plist
        guard let path = Bundle.main.path(forResource: "HMEmoticon", ofType: "bundle"), let bundle = Bundle(path: path), let plistPath = bundle.path(forResource: "emoticons.plist", ofType: nil), let array = NSArray(contentsOfFile: plistPath) as? [[String: String]], let models = NSArray.yy_modelArray(with: ZLEmotionPackage.classForCoder(), json: array) as? [ZLEmotionPackage] else{
            
            return
        }
        //设置表情包数据 
        //+= 不需要再分配空间字节追加数据
        packages += models

    }
    
}
